package com.cloud.code.牛客网;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * BM54 三数之和
 */
public class Test63 {

    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        //排序
        Arrays.sort(num);


        for (int i = 0; i < num.length; i++) {

            if (num[0] > 0) {
                break;
            }
            if (i > 0 && num[i - 1] == num[i]) {
                continue;
            }

            int left = i + 1;
            int right = num.length - 1;

            while (left < right) {

                int sum = num[i] + num[left] + num[right];
                if (sum == 0) {
                    ArrayList<Integer> tem = new ArrayList<>();
                    tem.add(num[i]);
                    tem.add(num[left]);
                    tem.add(num[right]);
                    res.add(tem);

                    while (left < num.length - 1 && num[left] == num[left + 1]) {
                        left++;
                    }

                    while (right > 0 && num[right] == num[right - 1]) {
                        right--;
                    }
                    left++;
                    right--;

                } else if (sum > 0) {
                    right--;
                } else {
                    left++;
                }

            }
        }


        return res;
    }
}
